﻿@page "/"
@using AntDesign;
@using System.Collections.ObjectModel
@using System.Text
@using WareHouseManagement.Common
@using WareHouseManagement.ModelEntity;
﻿@using System.ComponentModel
@using AntDesign.TableModels
@using System.Text.Json;
@using WareHouseManagement.Data
@using WareHouseManagement.Commom
@using static WareHouseManagement.Commom.EnumDefination
@inject IMessageService _message
@inject AG2WareHouseServer AG2WareHouseServer;
@inject InventoryServer InventoryServer
@inject IJSRuntime JSRuntime

<div style="margin:20px">
    <GridRow>
        <GridCol Span="16">
            <GridRow Style="width:100%">
                <GridRow Style="width:100%">
                    <h1 style="font-family: 'yuanti', sans-serif;">AGING2库位管理系统</h1>
                </GridRow>

                <GridRow Style="width:100%">
                    <Space>
                        <SpaceItem>
                            <Button Type="@ButtonType.Primary" OnClick="@Refresh">刷新</Button>
                        </SpaceItem>
                        <SpaceItem>
                            <Search Placeholder="请输入物料编码" @bind-Value="@txtValue" OnSearch="OnSearch" Style="width:100%" />
                        </SpaceItem>
                        <SpaceItem>
                            <GridCol Style="text-align:center;margin-left:10px">
                                <Switch @bind-Checked="switchValue" />
                                <Tag>按库位编码查询</Tag>
                            </GridCol>
                        </SpaceItem>
                        <SpaceItem>

                            <Button OnClick="@SaveFile">导出EXCEL</Button>
                        </SpaceItem>
                        <SpaceItem>
                            <Button OnClick="@Synchronization">盘点</Button>
                        </SpaceItem>
                    </Space>
                    @*   <GridCol Style="margin-right:10xp">
                    <Button  Style="margin-right:10xp">刷新</Button>
                    </GridCol>
                    <GridCol  >
                    <Search Placeholder="请输入物料编码" @bind-Value="@txtValue" OnSearch="OnSearch" Style="width:100%" />
                    </GridCol>
                    <GridCol>
                    <GridCol Style="text-align:center;margin-left:10px">
                    <Switch @bind-Checked="switchValue"/>
                    <Tag>按库位编码查询</Tag>
                    </GridCol>
                    </GridCol>*@
                </GridRow>
            </GridRow>
        </GridCol>

        <GridCol Span="8" style="text-align:right">
            <Image Src="/image/gh.jpg" Height="80" Preview=false Alt="这是一家很牛逼的公司"></Image>
        </GridCol>
    </GridRow>

    <br />
    <Table DataSource="listOfData"
           TItem="AG2Warehouse_Entity"
           RowClassName="@(_=>"editable-row")"
           Bordered TableLayout="fixed"
           Size="TableSize.Default">
        <ChildContent Context="data">
            <Column TData="string" Ellipsis Title="库位编码" Width="8%">
                @if (!editCache[data.Devid].edit)
                {
                    @data.Remark
                }
                else
                {
                    <Input @bind-Value="editCache[data.Devid].data.Remark" ReadOnly Style="border:none" />
                }
            </Column>
            <Column TData="string" Ellipsis Title="物料编码" Width="15%">
                @if (!editCache[data.Devid].edit)
                {
                    @data.Code
                }
                else
                {
                    <Input @bind-Value="editCache[data.Devid].data.Code" />
                }
            </Column>
            <Column TData="string" Title="LOT号" Ellipsis Width="15%">
                @if (!editCache[data.Devid].edit)
                {
                    @data.Lot
                }
                else
                {
                    <Input @bind-Value="editCache[data.Devid].data.Lot" />
                }
            </Column>
            <Column TData="string" Title="任务号" Ellipsis Width="15%">
                @if (!editCache[data.Devid].edit)
                {
                    @data.Task_NO
                }
                else
                {
                    <Input @bind-Value="editCache[data.Devid].data.Task_NO" />
                }
            </Column>
            <Column TData="string" Title="卷芯直径" Ellipsis Width="7%">
                @if (!editCache[data.Devid].edit)
                {
                    @data.TASK_Diam
                }
                else
                {
                    <Input @bind-Value="editCache[data.Devid].data.TASK_Diam" />

                }
            </Column>
            <Column TData="string" Title="宽幅" Ellipsis Width="7%">
                @if (!editCache[data.Devid].edit)
                {
                    @data.TASK_WIDTH
                }
                else
                {
                    <Input @bind-Value="editCache[data.Devid].data.TASK_WIDTH" />

                }
            </Column>
@*            <Column TData="string" Title="物料宽幅" Ellipsis Width="7%">
                @if (!editCache[data.Devid].edit)
                {
                    @data.TASK_WIDTH
                }
                else
                {
                    <Input @bind-Value="editCache[data.Devid].data.TASK_WIDTH" />

                }
            </Column>
            <Column TData="string" Title="米数" Ellipsis Width="7%">
                @if (!editCache[data.Devid].edit)
                {
                    @data.TASK_SIZE
                }
                else
                {
                    <Input @bind-Value="editCache[data.Devid].data.TASK_SIZE" />

                }
            </Column>*@

            <Column TData="string" Title="更新时间" Ellipsis Width="15%">
                @if (!editCache[data.Devid].edit)
                {
                    @data.UpdTime
                }
                else
                {
                    <Input @bind-Value="editCache[data.Devid].data.UpdTime" />

                }
            </Column>
            <Column TData="bool" Title="任务状态" Ellipsis Width="7%">

                @if (!editCache[data.Devid].edit)
                {
                    <Switch @bind-Value="@data.IsCreat"></Switch>
                }
                else
                {
                    <Switch @bind-Value="editCache[data.Devid].data.IsCreat"></Switch>
                }
            </Column>
            <Column TData="bool" Title="是否有料" Ellipsis Width="7%">

                @if (!editCache[data.Devid].edit)
                {
                    <Switch @bind-Value="@data.ISHave"></Switch>
                }
                else
                {
                    <Switch @bind-Value="editCache[data.Devid].data.ISHave"></Switch>

                }
            </Column>
            <Column TData="string" Title="物料类型" Ellipsis Width="7%" Style="align-content:center;padding:10px" >
             
                @if (!editCache[data.Devid].edit)
                {
                    <Select TItem="Val_Des"
                        TItemValue="int"
                        DataSource="EnumDefination.MaterialTypeList"
                        @bind-Value="@data.MaterialName"
                        DefaultValue="@(0)"
                        ValueName="@nameof(Val_Des.Val)"
                        LabelName="@nameof(Val_Des.Description)"
                         >
                    </Select>
                }
                else
                {
                       <Select TItem="Val_Des"
                        TItemValue="int"
                        DataSource="EnumDefination.MaterialTypeList"
                        @bind-Value="@editCache[data.Devid].data.MaterialName"
                        DefaultValue="@(0)"
                        ValueName="@nameof(Val_Des.Val)"
                        
                        LabelName="@nameof(Val_Des.Description)"
                        >
                </Select>
                }
            </Column>

            <Column TData="bool" Title="是否启用" Ellipsis Width="7%">

                @if (!editCache[data.Devid].edit)
                {
                    <Switch @bind-Value="@data.Isenable"></Switch>
                }
                else
                {
                    <Switch @bind-Value="editCache[data.Devid].data.Isenable"></Switch>
                }
            </Column>

            <ActionColumn Title="操作" Width="12%">
                @if (!editCache[data.Devid].edit)
                {
                    <a @onclick="() => startEdit(data.Devid)">修改</a>
                }
                else
                {
                    <a @onclick="() => saveEdit(data.Devid)" class="save">保存</a>
                    <a @onclick="() => ClearData(data.Devid)" class="save">清除数据</a>
                    @*  <a @onclick="() => Synchronization(data)" class="save">盘点</a>*@
                    @*<Popconfirm Title="是否取消"
                OnConfirm="() => cancelEdit(data.Devid)"
                OkText="是"
                CancelText="否">
                <a>取消</a>
                </Popconfirm>*@
                }
            </ActionColumn>
        </ChildContent>
    </Table>

</div>

<style>
    .save {
        margin-right: 8px;
    }
</style>

@code {

    record ItemData
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
    };

    //ObservableCollection<AG2Warehouse_Entity> datalist = new ObservableCollection<AG2Warehouse_Entity>();

    IDictionary<int, (bool edit, AG2Warehouse_Entity data)> editCache = new Dictionary<int, (bool edit, AG2Warehouse_Entity data)>();
    List<AG2Warehouse_Entity> listOfData = new();
    int i = 0;
    string editId;
    private string txtValue;
    private bool switchValue;
    void startEdit(int id)
    {
        var data = editCache[id];
        //editCache[id] = (true, data.data with ); // add a copy in cache
        editCache[id] = (true, data.data.Clone());

    }

    void cancelEdit(int id)
    {
        var data = listOfData.FirstOrDefault(item => item.Devid == id);
        editCache[id] = (false, data); // recovery
    }

    async void saveEdit(int id)
    {
        var index = listOfData.FindIndex(item => item.Devid == id);
        listOfData[index] = editCache[id].data; // apply the copy to data source
        editCache[id] = (false, listOfData[index]); // don't affect rows in editing
                                                    //更新数据
        string result = await AG2WareHouseServer.UpdataAG2(listOfData[index]);
        await _message.Info(result);
    }

    protected override void OnInitialized()
    {
        _message.Config(new MessageGlobalConfig
            {
                Top = 20,
                Duration = 3,
                MaxCount = 3,
                Rtl = true,
            });
        var data = AG2WareHouseServer.GetAG2Warehouse_Entites();
        if (data != null)
        {
            listOfData = data.OrderBy(x => x.Devid).ToList();
        }

        if (listOfData != null)
        {
            listOfData.ForEach(item =>
            {
                editCache[item.Devid] = (false, item);
            });
        }

    }
    //筛选数据
    public async void OnSearch()
    {
        if (string.IsNullOrEmpty(txtValue))
        {
            await _message.Info("请输入LOT号或库位编码");
            return;
        }
        if (!switchValue)
        {
            var databyLot = listOfData.FirstOrDefault(x => x.Lot == txtValue);
            if (databyLot == null)
            {
                await _message.Info("未查询库位查询到该信息");
                return;
            }
            i = 0;
            listOfData.Clear();
            editCache.Clear();

            listOfData.Add(databyLot);
            editCache.Add(databyLot.Devid, (false, databyLot));
        }
        var databyid = listOfData.FirstOrDefault(x => x.Remark == txtValue);
        if (databyid == null)
        {
            await _message.Info("未查询库位查询到该信息");
            return;
        }
        i = 0;
        listOfData.Clear();
        editCache.Clear();

        listOfData.Add(databyid);
        editCache.Add(databyid.Devid, (false, databyid));
    }
    public async void Synchronization()
    {
        var listOfData = AG2WareHouseServer.GetAG2Warehouse_Entites().OrderBy(x => x.Devid).ToList(); ;
        List<A07Par> a07Pars = new List<A07Par>();
        foreach (var item in listOfData)
        {
            a07Pars.Add(new A07Par()
                {
                    POSITION = item.Remark,
                    TASK_CODE = item.Code,
                    TASK_Diam = item.TASK_Diam,
                    TASK_Diam_SIZE = item.TASK_Diam_SIZE,
                    TASK_LOTID = item.Lot,
                    TASK_SIZE = item.TASK_SIZE,
                    TASK_WIDTH = item.TASK_WIDTH
                });
        }
        var result = await InventoryServer.MakeInventory(a07Pars);
        await _message.Info(result.MESSAGE);

    }
    public async Task Refresh()
    {
        i = 0;
        listOfData.Clear();
        editCache.Clear();

        listOfData = AG2WareHouseServer.GetAG2Warehouse_Entites().OrderBy(x => x.Devid).ToList();
        if (listOfData != null)
        {
            listOfData.ForEach(item =>
            {
                editCache[item.Devid] = (false, item);

            });
        }

    }
    private Stream GetFileStream()
    {
        var randomBinaryData = new byte[50 * 1024];
        var fileStream = new MemoryStream(randomBinaryData);

        return fileStream;
    }
    private async Task SaveFile()
    {
        //var fileStream = GetFileStream();
        // var fileName = "log.bin";

        // using var streamRef = new DotNetStreamReference(stream: fileStream);

        // await JSRuntime.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
        Dictionary<string, string> colunmNmae = new Dictionary<string, string>();
        colunmNmae.Add("Remark", "库位编号");
        colunmNmae.Add("Task_NO", "任务号");
        colunmNmae.Add("Code", "物料编码");
        colunmNmae.Add("Lot", "LOT号");

        colunmNmae.Add("TASK_Diam", "卷芯规格");
        colunmNmae.Add("TASK_Diam_SIZE", "卷芯直径");
        colunmNmae.Add("TASK_WIDTH", "卷芯宽幅");
        colunmNmae.Add("UpdTime", "更新时间");
        var Data = AG2WareHouseServer.GetAG2Warehouse_Entites().OrderBy(x => x.Devid).ToList();
        var exceldata = NPOIService.ExportToExcel(Data, colunmNmae, 1);
        string fileName = DateTime.Now.ToString("yyyyMMddHHmmss");
        await SaveToFile(exceldata, fileName);
        await _message.Info("导出EXCEL成功");
    }
    public async Task SaveToFile(byte[] data, string fileName)
    {

        //var filePath = Path.Combine(@"C:\Users\user\Desktop", $"{fileName}.xlsx");

        var fileStream = new MemoryStream(data);

        using var streamRef = new DotNetStreamReference(stream: fileStream);

        await JSRuntime.InvokeVoidAsync("downloadFileFromStream", $"{fileName}.xlsx", streamRef);
        // await File.WriteAllBytesAsync(filePath,data);
    }
    public async Task ClearData(int id)
    {
        var index = listOfData.FindIndex(item => item.Devid == id);
        var data = editCache[id].data;

        data.TASK_Diam=string.Empty;
        data.TASK_Diam_SIZE=string.Empty;
        data.Task_NO=string.Empty;
        data.TASK_SIZE=string.Empty;
        data.TASK_WIDTH = string.Empty;
        data.UpdTime=string.Empty;
        data.IsCreat=false;
        data.ISHave = false;
        data.Lot=string.Empty;
        data.Code = string.Empty;
        data.MaterialName = (int)MaterialType.EmptyShelf;

        listOfData[index] = data; // apply the copy to data source
        editCache[id] = (false, listOfData[index]); // don't affect rows in editing
                                                    //更新数据
        string result = await AG2WareHouseServer.UpdataAG2(listOfData[index]);
        await _message.Info(result);
    }
}

@code
{
    //    #region 之前的代码
    //    <div style="margin:20px">
    //        <GridRow>
    //            <GridCol Span="8">
    //                <GridRow>
    //                    <GridRow>
    //                        <h1 style="font-family: 'yuanti', sans-serif;">AGING2库位管理系统</h1>
    //                    </GridRow>
    //                    <GridRow>
    //                        <GridCol>
    //                            <Search Placeholder="请输入物料编码" @bind-Value="@txtValue" OnSearch="OnSearch" />
    //                        </GridCol>
    //                        <GridCol Span="8">
    //                            <GridCol Span="8" Style="text-align:center;margin-left:10px">
    //                                <Space Size="@("small")" >
    //                                    <SpaceItem>
    //                                        <Switch @bind-Checked="switchValue" />
    //                                    </SpaceItem>
    //                                    <SpaceItem>
    //                                        <Tag>按库位编码查询</Tag>
    //                                    </SpaceItem>
    //                                </Space>
    //                            </GridCol>
    //                        </GridCol>
    //                    </GridRow>
    //                </GridRow>
    //            </GridCol>

    //            <GridCol Span="8" Offset="8" style="text-align:right">
    //                <Image Src="/image/gh.jpg" Height="80" Preview=false Alt="这是一家很牛逼的公司"></Image>
    //            </GridCol>
    //        </GridRow>

    //        <br />
    //        <Table @ref="table"
    //           TItem="AG2Warehouse_Entity"
    //           DataSource="@datalist"
    //           Total="_total"
    //               @bind-PageIndex="_pageIndex"
    //               @bind-PageSize="_pageSize"
    //               @bind-SelectedRows="selectedRows"
    //           OnChange="OnChange"
    //           Size="TableSize.Small"
    //           Bordered=@true
    //           Style="font-size:25px"
    //               >

    //            <PropertyColumn Title="库位编号" Property="c=>c.Remark" Sortable />

    //            <PropertyColumn Title="物料编码" Property="c=>c.Code"  />
    //            <PropertyColumn Title="任务号" Property="c=>c.Task_NO"   />
    //            <PropertyColumn Title="LOT号" Property="c=>c.Lot"   />
    //            <PropertyColumn Title="任务状态" Property="c=>c.IsCreat">
    //                <Switch @bind-Value="@context.IsCreat"></Switch>
    //            </PropertyColumn>
    //            <PropertyColumn Title="是否有料" Property="c=>c.ISHave">
    //                <Switch @bind-Value="@context.ISHave"></Switch>
    //            </PropertyColumn>
    //            <PropertyColumn Title="是否启用" Property="c=>c.Isenable">
    //                <Switch @bind-Value="@context.Isenable"></Switch>
    //            </PropertyColumn>

    //            <PropertyColumn Property="c=>c.UpdTime" Format="yyyy-MM-dd" />
    //            <ActionColumn Width="20">

    //                <Space Size="@("middle")">
    //                    <SpaceItem><Button OnClick="()=>Delete(context.Devid)">更新</Button></SpaceItem>
    //                    <SpaceItem><Button OnClick="()=>Delete(context.Devid)">同步</Button></SpaceItem>
    //                </Space>

    //            </ActionColumn>
    //        </Table>
    //    </div>

        //    @code {


    //AG2Warehouse_Entity[] datalist;
    //IEnumerable<AG2Warehouse_Entity> selectedRows;

        //ITable table;

    //int _pageIndex = 1;
    //int _pageSize = 10;
    //int _total = 0;
    //private string txtValue;
    //private bool switchValue;
    //protected override async Task OnInitializedAsync()
    //{
    //    datalist = await GetForecastAsync(1, 50);
    //    _total = 50;
    //}


    //public async Task OnChange(QueryModel<AG2Warehouse_Entity> queryModel)
    //{
    //    Console.WriteLine(JsonSerializer.Serialize(queryModel));
    //}

    //public Task<AG2Warehouse_Entity[]> GetForecastAsync(int pageIndex, int pageSize)
    //{
    //    var rng = new Random();
    //    return Task.FromResult(Enumerable.Range((pageIndex - 1) * pageSize + 1, pageSize).Select(index =>
    //    {
    //        var temperatureC = rng.Next(-20, 55);
    //        return new AG2Warehouse_Entity
    //        {
    //            Devid = 1,
    //            Task_NO = "123",
    //            Lot = "1234",
    //            Code = "w123",
    //            UpdTime = DateTime.Now.ToString()
    //        };
    //    }).ToArray());
    //}

    //public void RemoveSelection(int deviceid)
    //{
    //    var selected = selectedRows.Where(x => x.Devid != deviceid);
    //    selectedRows = selected;
    //}

    //private void Delete(int deviceid)
    //{
    //    datalist = datalist.Where(x => x.Devid != deviceid).ToArray();
    //    _total = datalist.Length;
    //}
    //private void OnSearch()
    //{

    //}
    //    }
        //    #endregion
}








